<?php

/**
 * This is the model class for table "game".
 *
 * The followings are the available columns in table 'game':
 * @property integer $id
 * @property string $name
 * @property integer $category_id
 * @property string $sapo
 * @property string $description   
 * @property integer $hot
 * @property integer $status
 * @property string $meta_title
 * @property string $meta_keyword
 * @property string $meta_description
 *
 * The followings are the available model relations:
 * @property Category $category
 * @property GameDownload[] $gameDownloads
 * @property GameImageLink[] $gameImageLinks
 */
class Game extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Game the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'game';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name, code_identifier, hot, status', 'required'),
            array('category_id, hot, status', 'numerical', 'integerOnly' => true),
            array('name', 'length', 'max' => 256),
            array('sapo,description, rule, url, vote', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, name, category_id, sapo, description, hot, status, code_identifier, meta_title, meta_keyword, meta_description', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'category' => array(self::BELONGS_TO, 'GameCategory', 'category_id'),
            'gamePlatform' => array(self::HAS_MANY, 'GamePlatform', 'game_id'),                        
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'name' => 'Tên',
            'category_id' => 'Danh mục',
            'sapo'=> 'Miêu tả ngắn',
            'description' => 'Chi tiết',                        
            'hot' => 'Nổi bật',
            'status' => 'Trạng thái',
            'code_identifier' => 'Code_identifier',
            'meta_title' => 'Thẻ tiêu đề',
            'meta_keyword' => 'Từ khóa',
            'meta_description' => 'Thẻ miêu tả',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('category_id', $this->category_id);
        $criteria->compare('description', $this->description, true);        
        $criteria->compare('status', $this->status);
        $criteria->compare('code_identifier', $this->code_identifier);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function getCurrentVersion($platform_name = "web") {      
        $platformModel = Platform::model()->find('code_identifier=:code_identifier', array(':code_identifier'=>$platform_name));
        if(!isset($platformModel))
            return FALSE;
        $gamePlatformModel = GamePlatform::model()->find('game_id=:game_id AND platform_id=:platform_id', array(':game_id'=>$this->id, ':platform_id'=>$platformModel->id));        
        if(!isset($gamePlatformModel))
            return FALSE;
        $criteria = new CDbCriteria;
        $criteria->addCondition('game_platform_id =:game_platform_id');        
        $criteria->addCondition('enabled = 1');
        $criteria->params = array(':game_platform_id'=>$gamePlatformModel->id);
        $version = GameVersion::model()->find($criteria);
        if (!isset($version))
            return FALSE;                    
        return $version;
    }
    
    public function getCountDownload(){
        $total = 0;
        $criteria = new CDbCriteria;
        $criteria->alias = "game_version";         
        $criteria->join .= ' INNER JOIN game_platform ON game_version.game_platform_id = game_platform.id';
        $criteria->join .= ' INNER JOIN game ON game.id = game_platform.game_id';
        $criteria->addCondition('game.id = '.$this->id);        
        $models = GameVersion::model()->findAll($criteria);
        if(!isset($models))
            return FALSE;
        foreach($models as $model){
            $total += $model->download_times;
        }
        return $total;
    }
    
    public function getCurrentVersionDetail(){
        $criteria = new CDbCriteria;
        $criteria->alias = "game_version";        
        $criteria->join .= ' INNER JOIN game_platform ON game_version.game_platform_id = game_platform.id';
        $criteria->join .= ' INNER JOIN game ON game.id = game_platform.game_id';
        $criteria->join .= ' INNER JOIN platform ON platform.id = game_platform.platform_id';
        $criteria->addCondition(' (platform.code_identifier = "ios" OR platform.code_identifier="android") AND game_version.enabled = 1 AND game_version.visible = 1 AND game.id='.$this->id);
        $models = GameVersion::model()->findAll($criteria);
        if(!isset($models))
            return FALSE;
        else
            return $models;
    }  
    
    public function resizeImage($height = NULL, $width = NULL, $path = NULL, $ratio = NULL) {
        //Get old size
        list($oldWidth, $oldHeight) = getimagesize($this->image);
        //Get path
        if ($path == NULL)
            $newPath = $this->image;
        // Get new sizes
        if ($ratio) {
            $newWidth = $ratio * $oldWidth;
            $newHeight = $ratio * $oldHeight;
        } if ($height == NULL && $width != NULL) {
            $newHeight = $oldHeight * $width / $oldWidth;
            $newWidth = $width;
        } else if ($width == NULL && $height != NULL) {
            $newWidth = $oldWidth * $height / $oldHeight;
            $newHeight = $height;
        } else {
            $newWidth = $width;
            $newHeight = $height;
        }
        // Get type of image
        $info = getimagesize($this->image);
        $type = $info[2];
        $thumb = imagecreatetruecolor($newWidth, $newHeight);
        imagealphablending($thumb, false);
        imagesavealpha($thumb, true);
        if ($type === IMAGETYPE_JPEG)
            $source = imagecreatefromjpeg($this->image);
        else if ($type === IMAGETYPE_PNG)
            $source = imagecreatefrompng($this->image);
        else
            return FALSE;
        // Resize
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight); // Output
        if ($type === IMAGETYPE_JPEG)
            if (imagejpeg($thumb, $newPath))
                return TRUE;
            else
                return FALSE;
        else if ($type === IMAGETYPE_PNG)
            if (imagepng($thumb, $newPath))
                return TRUE;
            else
                return FALSE;
    }
}